package com.jvyou.thread.test05;

import java.util.Random;

/**
 * @author 橘柚
 * @version 1.0-SNAPSHOT
 * @Date 2024/7/31 16:38
 * @Description 抽奖
 */
public class Lottery implements Runnable {
    // 奖池
    private final int[] numbers;
    // 剩余的奖品数量
    private int count;

    Lottery(int[] numbers) {
        this.numbers = numbers;
        this.count = numbers.length;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                if (count <= 0) {
                    System.out.println(Thread.currentThread().getName() + ">抽奖结束");
                    break;
                } else {
                    int index = (int) (Math.random() * numbers.length);
                    if (numbers[index] != 0) {
                        System.out.println(Thread.currentThread().getName() + ">抽到了" + numbers[index]);
                        numbers[index] = 0;
                        count--;
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        int[] numbers = {10, 5, 20, 50, 100, 200, 500, 800, 2, 80, 300, 700};
        Lottery lottery = new Lottery(numbers);
        for (int i = 0; i < 10; i++) {
            Thread t = new Thread(lottery, "抽奖员" + i);
            t.setPriority(new Random().nextInt(9) + 1);
            t.start();
        }
    }
}
